import { computed } from 'vue'
import { RouteRecordRaw } from 'vue-router'
import usePermission from '@renderer/hooks/permission'
import { useAppStore, useUserStore } from '@renderer/store'
import appClientMenus from '@renderer/router/app-menus'

export default function useMenuTree() {
  const permission = usePermission()
  const appStore = useAppStore()
  const appRoute = computed(() => {
    if (appStore.menuFromServer) {
      return appStore.appAsyncMenus
    }
    return appClientMenus
  })
  const menuTree = computed(() => {
    let menuName: any[] = []
    // 根据角色动态添加菜单
    const userInfo = useUserStore().localUserInfo
    switch (userInfo.isAdmin) {
      case 1:
        // 管理员
        menuName = ['financialSys', 'productionSys']
        break
      case 2:
        // 生产
        menuName = ['productionSys']
        break
      case 3:
        // 财务
        menuName = ['productionSys', 'financialSys']
        break
      case 4:
        // 超管
        menuName = ['userSys', 'productionSys', 'financialSys']
        break
      default:
        break
    }

    const copyRouter = appRoute.value.filter((item) => menuName.includes(item.name!))

    copyRouter.sort((a: RouteRecordRaw, b: RouteRecordRaw) => {
      return (a.meta?.order || 0) - (b.meta?.order || 0)
    })

    function travel(_routes: RouteRecordRaw[], layer: number) {
      if (!_routes) return null

      const collector: any = _routes.map((element) => {
        // no access
        if (!permission.accessRouter(element)) {
          return null
        }

        // leaf node
        if (element.meta?.hideChildrenInMenu || !element.children) {
          element.children = []
          return element
        }

        // route filter hideInMenu true
        element.children = element.children.filter((x) => x.meta?.hideInMenu !== true)

        // Associated child node
        const subItem = travel(element.children, layer + 1)

        if (subItem.length) {
          element.children = subItem
          return element
        }
        // the else logic
        if (layer > 1) {
          element.children = subItem
          return element
        }

        if (element.meta?.hideInMenu === false) {
          return element
        }

        return null
      })
      return collector.filter(Boolean)
    }

    return travel(copyRouter, 0)
  })

  return {
    menuTree
  }
}
